/*
 * @Author: 何 海深 813936564@qq.com
 * @Date: 2022-08-10 18:09:46
 * @LastEditors: 何 海深 813936564@qq.com
 * @LastEditTime: 2024-02-01 17:45:08
 * @FilePath: \show-data-vue3\src\utils\axios.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import axios, { type AxiosResponse } from 'axios'
import selfMessageIndex from '@/components/self-message/selfMessageIndex'
/* import { doLoginOut } from '@/hooks/userOutIn' */
import stores from '@/stores/index'
import { doExitSystem } from '@/hooks/userOutLogin/userOutLoginIndex'
/* const exitSystemClearInfo = async () => {
  const casEnable = JSON.parse(localStorage.getItem('ststemloginType') as string)
  sessionStorage.clear() // 清除sessionStorage缓存
  localStorage.clear() // 清除localStorage缓存
  // 清除cookie
  // eslint-disable-next-line no-useless-escape
  const keys = document.cookie.match(/[^ =;]+(?=\=)/g)
  if (keys) {
    for (let i = keys.length; i--; ) {
      document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
  }
  if (casEnable) {
    const jumpUrl =
      location.host === '130.120.3.108'
        ? 'https://xtbg.digitalgd.com.cn'
        : 'https://xtbg.gdzwfw.gov.cn'
    const backUrl = `${location.protocol}//${location.host}/pymbp/login#/`
    window.location.href = `${jumpUrl}/zwrz/rz/sso/logout?client_id=zwrz_pyczczl&backurl=${decodeURIComponent(
      backUrl
    )}`
    return false
  } else {
    return true
  }
} */
const showStatus = async (status: number): Promise<any> => {
  let message = ''
  switch (status) {
    case 400:
      message = '请求错误(400)'
      break
    case 401:
      message = '未授权，请重新登录(401)'
      selfMessageIndex.error(message)
      if (import.meta.env.MODE === 'development') {
        console.error('401,请重新登录')
      } else {
        await doExitSystem()
      }
      break
    case 403:
      message = '拒绝访问(403)'
      break
    case 404:
      message = '请求出错(404)'
      break
    case 408:
      message = '请求超时(408)'
      break
    case 500:
      message = '服务器错误(500)'
      break
    case 501:
      message = '服务未实现(501)'
      break
    case 502:
      message = '网络错误(502)'
      break
    case 503:
      message = '服务不可用(503)'
      break
    case 504:
      message = '网络超时(504)'
      break
    case 505:
      message = 'HTTP版本不受支持(505)'
      break
    default:
      message = `连接出错(${status})!`
  }
  return `${message}，请检查网络或联系管理员！`
}

const servers = axios.create({
  // baseURL: import.meta.env.VITE_RES_URL, //接口统一域名
  timeout: 30000, //设置超时
  headers: {
    'Content-Type': 'application/json;charset=UTF-8;'
  },
  withCredentials: false
})
//请求拦截器
servers.interceptors.request.use(
  async (config: any) => {
    const token = window.localStorage.getItem('token')
    token && (config.headers.token = `${token}`)
    //若请求方式为post，则将data参数转为JSON字符串
    if (config.method === 'POST' || config.method === 'post') {
      config.data = JSON.stringify(config.data)
    }
    return config
  },
  (error) =>
    // 对请求错误做些什么
    Promise.reject(error)
)

//响应拦截器
servers.interceptors.response.use(
  async (response) => {
    //响应成功
    showStatus(response?.status)
    // 打开注释执行脱敏逻辑
    /* if (
      isFilterUrlAndConfig(response) &&
      isDesensitization()
    ) {
      // 用作数据过滤
        const resType: string = toString.call(response.data.data).slice(8, -1)
        if (resType === 'Array') {
          await handleResPonseArrayData(response.data.data)
          return response.data
        } else if (resType === 'Object') {
          await handleResPonseObjData(response.data.data)
          return response.data
        } else {
          return response.data
        }
    } else {
      return response.data
    } */
    return response.data
  },
  (error) => {
    console.log('错误', error)
    //响应错误
    if (error.response && error.response.status) {
      const status = error.response.status
      showStatus(status)
      return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)
// 执行过敏
// 判断url和返回的数据是否符合脱敏格式
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const isFilterUrlAndConfig = (response: AxiosResponse): boolean => {
  const filterArrList = [
    '/one-map-api/pyVedioMonitor/selectVedioListByOrgan', // 融合通信监控设备
    '/one-map-api/communication/getTerminalList', // 融合通信-会议终端
    '/one-map-api/communication/selectTerminalTreeList' // 会议终端树
  ]
  if (
    !filterArrList.includes(response.config.url as string) &&
    response.headers &&
    response.headers['content-type'] === 'application/json' &&
    response.data &&
    response.data.code === 200 &&
    (toString.call(response.data?.data).slice(8, -1) === 'Array' ||
      toString.call(response.data?.data).slice(8, -1) === 'Object')
  ) {
    return true
  } else {
    return false
  }
}
// 判断是否需要脱敏的权限
export const isDesensitization = (): boolean => {
  if (stores.state.value.common.userInfo) {
    const roles = stores.state.value.common.userInfo?.principal?.userRoles
    if (roles.length) {
      let isShowCurrent = null
      isShowCurrent = roles.find((i: any) => {
        if (['1', '2'].includes(i)) {
          return i
        }
        // 一张图查看角色: map=3
        // 一张图数据解除脱敏:  nodesen=2
        // 管理员: admin=1
        /*  if (["admin", "nodesen"].includes(i.roleKey)) {
          return i;
        } */
      })
      if (isShowCurrent) {
        return false
      } else {
        return true
      }
    } else {
      return true
    }
  } else {
    return true
  }
}
// 数组脱敏
const handleResPonseArrayData = async (arr: any) => {
  if (arr.length) {
    arr.forEach((item: any) => {
      handleResPonseObjData(item)
    })
  } else {
    return []
  }
}
// 对象脱敏
const handleResPonseObjData = async (params: any) => {
  const reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
  const _IDRe18 = // 18位身份证
    /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  const _IDre15 = // 15位身份证
    /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
  const keyArr = [
    'name',
    'xcfzrxm',
    'lxr',
    'qyfzr',
    'frhfzr',
    'fzr',
    'qyfzr',
    'fddbr',
    'tccfzr',
    'actualOperatorName',
    'principalName',
    'policeName', // 民警名称
    'jhr', // 监护人
    'xm', // 残疾人姓名
    'dzzlxr',
    'dzzsj',
    'dyxm',
    'zzfsj',
    'zzwy',
    'xcwy',
    'jjwy',
    'qnwy',
    'wtwy',
    'bmwy',
    'czxm',
    'dymc',
    'chairman',
    'deputyChairman',
    'deputyPartySecretary',
    'deputyVillageCommitteeDirector',
    'director',
    'partyCommitteeMember',
    'partySecretary',
    'villageCommitteeDirector',
    'villageCommitteeMember',
    'wgdzbsjxm'
  ]
  for (const key in params) {
    if (keyArr.findIndex((item) => item === key) > -1 && params[key]) {
      // 姓名电话号码替换
      params[key + 'Copy'] = params[key]
      const str = params[key]
      const regExp = /13[0-9]\d{8}$/g
      const val = str.match(regExp)
      //处理姓名与电话拼接脱敏
      if (val) {
        const tel = val[0]
        const mobile = tel.replace(tel.slice(tel.length - 8, tel.length - 4), '****')
        const name = params[key].replace(tel, '')
        const replaceSlice: string = name.slice(1, name.length === 2 ? 2 : name.length - 1)
        params[key] = name.replace(replaceSlice, '*') + mobile
      } else {
        //姓名脱敏
        if (params[key].indexOf('、') != -1) {
          const arr = params[key].split('、')
          let str = ``
          arr.forEach((e: any, i: number) => {
            const replaceSlice: string = e.slice(1, e.length === 2 ? 2 : e.length - 1)
            e = e.replace(replaceSlice, '*')
            str += i == arr.length - 1 ? e : `${e}、`
          })
          params[key] = str
        } else {
          const replaceSlice: string = params[key].slice(
            1,
            params[key].length === 2 ? 2 : params[key].length - 1
          )
          params[key] = params[key].replace(replaceSlice, '*')
        }
      }
    } else if (reg_tel.test(params[key])) {
      // 电话号码替换
      const str = params[key]
      params[key + 'Copy'] = params[key]
      params[key] = str.replace(str.slice(str.length - 8, str.length - 4), '****')
    } else if (
      key === 'certificateNo' ||
      key === 'sfzh' ||
      key === 'cjrz' ||
      _IDRe18.test(params[key]) ||
      _IDre15.test(params[key])
    ) {
      params[key + 'Copy'] = params[key]
      const certificateNo = params[key].replace(/^(.{6})(?:\d+)(.{2})$/, '$1**********$2')
      params[key] = certificateNo
    } else {
      const valueType = toString.call(params[key]).slice(8, -1)
      if (valueType === 'Array') {
        await handleResPonseArrayData(params[key])
      }
      if (valueType === 'Object') {
        await handleResPonseObjData(params[key])
      }
    }
  }
}
export default servers
